package org.itver.arm.controls.behaviors;


import com.sun.j3d.utils.picking.PickResult;
import com.sun.j3d.utils.picking.behaviors.PickMouseBehavior;
import javax.media.j3d.BoundingSphere;
import javax.media.j3d.Bounds;
import javax.media.j3d.BranchGroup;
import javax.media.j3d.Canvas3D;
import org.itver.arm.models.elements.Piece;

public class PickPieceBehavior extends PickMouseBehavior{
    private Piece   last;
    private boolean active;

    public PickPieceBehavior(Canvas3D canvas, BranchGroup root, Bounds bounds){
        super(canvas, root, bounds);
        this. active = true;
        this.pickCanvas.setTolerance(0.0f);
    }

    public PickPieceBehavior(Canvas3D canvas, BranchGroup root){
        this(canvas, root, new BoundingSphere());
    }
    
    @Override
    public void updateScene(int xpos, int ypos) {
        if((mevent.getClickCount() < 2) || (!isActive()))
            return;
        PickResult result = null;
        pickCanvas.setShapeLocation(xpos, ypos);
        result = pickCanvas.pickClosest();
        if(last != null)
            last.setSelected(false);
        if (result != null) {
            if(result.getObject().getUserData() instanceof Piece){
                Piece picked = (Piece) result.getObject().getUserData();
                if(picked == null)
                    return;
                picked.setSelected(true);
                last = picked;
            }
	}
        else
            last = null;
    }

    /**
     * @return the active
     */
    public boolean isActive() {
        return active;
    }

    /**
     * @param active the active to set
     */
    public void setActive(boolean active) {
        this.active = active;
    }
}